package com.etc.test3.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author MaZheng
 * @since 2020/12/23 - 16:18
 */

public class AProxyDynamicTool implements InvocationHandler {

    // 所有运行方法的时候，都会运行invoke
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object o = null;
        try {
            System.out.println("-------before----------");
            // 反射 调用方法
            o = method.invoke(target, args); // A.a1() | A.a2()
            System.out.println("-------after returning----------");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("--------catch exception---------------------");
        } finally {
            System.out.println("----------finally after----------------------------");
        }

        return o;
    }

    public AInterface newInstans() {

        // 创建代理对象
        // jvm运行时, 调用的是 代理对象
        return (AInterface) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{AInterface.class}, this);
    }

    private AInterface target;

    public AProxyDynamicTool() {
    }

    public AProxyDynamicTool(AInterface target) {
        this.target = target;
    }


}
